package com.example.demo.rabbitMQ.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Description:  </p>
 *
 * @author Eric Lee
 * @version v1.0.0
 * @since 2021/8/3 16:23
 **/
@Slf4j
public class RabbitMqCallback implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {

    /**
     * 消息发送成功的回调,开启发送确认.
     *
     * @param correlationData
     * @param ack
     * @param cause
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        //correlationData必须在发送的时候设置，否则将会使null，如下：
        //CorrelationData correlationData = new CorrelationData("1");
        //rabbitTemplate.convertAndSend("OrderDispathExchange","kk",
        //       "{\"msgId\":1,\"data\":\"测试\"}",correlationData);
        log.info("消息唯一标识: {}", correlationData);
        log.info("确认状态: {}", ack);
        if (!ack) {
            log.info("造成原因: {}", cause);
        }
    }

    /**
     * 消息发送失败返回监听器
     *
     * @param returnedMessage
     */
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        Map<String, String> hashMap = new HashMap<>();
        System.out.println(Charset.defaultCharset().name());
        String json = new String(returnedMessage.getMessage().getBody());
        System.out.println(hashMap.toString());
        System.out.println("交换器为===" + returnedMessage.getExchange());
        System.out.println("消息key为===" + returnedMessage.getRoutingKey());
        System.out.println("回复错误码为===" + returnedMessage.getReplyCode());
        System.out.println("回复内容为===" + returnedMessage.getReplyText());
    }


}
